<!DOCTYPE HTML>

<html>
<head>
<title>Repeatedly Drawing WebGL to 2D Canvas Must Show Only Latest Result</title>
<style type="text/css">
.nomargin {
  margin: 0px auto;
}
</style>

<script>
function sendResult(status, detail) {
  console.log(detail);
  if (window.domAutomationController) {
    window.domAutomationController.send(status);
  } else {
    console.log(status);
  }
}

var gl;
var fbo;
const sz = 256;
var numFramesBeforeBlit = 15;
var numFramesBeforeEnd = 15;

function drawTo2DCanvas(c2, webGLCanvas) {
  // Always clear 2D canvas to solid green first.
  c2.clearRect(0, 0, sz, sz);
  c2.fillStyle = 'rgb(0,255,0)';
  c2.fillRect(0, 0, sz, sz);
  // Draw WebGL canvas to this canvas.
  c2.drawImage(webGLCanvas, 0, 0);
}

function main() {
  let c2 = document.getElementById('canvas-2d').getContext('2d');
  let webGLCanvas = document.createElement('canvas');
  webGLCanvas.width = sz;
  webGLCanvas.height = sz;
  // Even though alpha:true is the default, specify it explicitly in order
  // to make this clear. (The test won't pass without it, anyway.)
  let gl = webGLCanvas.getContext('webgl', {alpha: true});
  if (!gl) {
    sendResult("FAILURE", "WebGL context not supported");
    return;
  }

  // Clear left half of WebGL canvas to red and right half to
  // transparent black.
  gl.disable(gl.SCISSOR_TEST);
  gl.clearColor(0.0, 0.0, 0.0, 0.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.scissor(0, 0, sz / 2, sz);
  gl.enable(gl.SCISSOR_TEST);
  gl.clearColor(1.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  // Draw to 2D canvas.
  drawTo2DCanvas(c2, webGLCanvas);

  // Clear right half of WebGL canvas to red and left half to
  // transparent black.
  gl.disable(gl.SCISSOR_TEST);
  gl.clearColor(0.0, 0.0, 0.0, 0.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.scissor(sz / 2, 0, sz / 2, sz);
  gl.enable(gl.SCISSOR_TEST);
  gl.clearColor(1.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  // Draw to 2D canvas.
  drawTo2DCanvas(c2, webGLCanvas);

  // Clear WebGL canvas to transparent black.
  gl.disable(gl.SCISSOR_TEST);
  gl.clearColor(0.0, 0.0, 0.0, 0.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  // Draw to 2D canvas.
  drawTo2DCanvas(c2, webGLCanvas);

  // 2D canvas should be green. Harness will verify this.
  waitForFinish();
}

function waitForFinish() {
  if (--numFramesBeforeEnd == 0) {
    sendResult("SUCCESS", "Test complete");
  } else {
    window.requestAnimationFrame(waitForFinish);
  }
}
</script>
</head>
<body onload="main()">
<canvas id="canvas-2d" width="256" height="256" class="nomargin" style="position:absolute; top:0px; left:0px"></canvas>
</div>
</body>
</html>
